package com.it.gw.modules.station.adapter

import PictureVo
import android.content.Context
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.it.common.utils.GlideUtils
import com.it.common.utils.isNotEmpty
import com.it.gw.R
import com.it.gw.databinding.ItemPicInfoBinding
import java.io.File


class PicListAdapter(
    var context: AppCompatActivity,
    var listener: (PictureVo) -> Unit,
    var delete: (PictureVo) -> Unit,
    var datas: List<PictureVo>
) : RecyclerView.Adapter<PicListAdapter.ViewHolder>() {
    companion object {
        const val TAG = "PicListAdapter"
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ViewHolder {
        val binding = ItemPicInfoBinding.inflate(LayoutInflater.from(parent.context))
        return ViewHolder(binding)
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data = datas[position]
        Log.d(TAG, "onBindViewHolder: $data")
        holder.binding.name.text = data.picnm

        if (data.filePath.isNotEmpty()) {
            GlideUtils.loadFile(context, data.filePath!!, holder.binding.ivPic)
            if (data.isEdit == true) {
                holder.binding.ivClose.visibility = View.VISIBLE
            } else {
                holder.binding.ivClose.visibility = View.GONE
            }


        } else if (data.pic_Url.isNotEmpty()) {
            val fileTarget = FileTarget(holder.binding.ivPic,data,context)
            Glide.with(context).asFile()
                .load(data.pic_Url!!)
                .into(fileTarget)
            if (data.isEdit == true) {
                holder.binding.ivClose.visibility = View.VISIBLE
            } else {
                holder.binding.ivClose.visibility = View.GONE
            }

        } else {
            GlideUtils.loadRes(context, R.drawable.icon_add_pic, holder.binding.ivPic)
            holder.binding.ivClose.visibility = View.GONE
        }


        holder.binding.ivClose.setOnClickListener {
            delete.invoke(data)
        }
        holder.binding.ivPic.setOnClickListener {
            listener.invoke(data)
        }
    }


    override fun getItemCount() = datas.size

    class ViewHolder(val binding: ItemPicInfoBinding) : RecyclerView.ViewHolder(binding.root)
}